<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>读书室</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .upload-area {
            border: 2px dashed #ccc;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            margin-bottom: 20px;
            cursor: pointer;
        }
        .upload-area:hover {
            background-color: #f0f0f0;
        }
        .main-container {
            display: flex;
            gap: 20px;
            margin-top: 20px;
        }
        .book-list {
            flex: 1;
            min-width: 250px;
            max-width: 300px;
        }
        .content-viewer-container {
            flex: 2;
            min-width: 400px;
        }
        .book-item {
            border: 1px solid #ddd;
            padding: 6px;
            margin-bottom: 6px;
            border-radius: 4px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .book-item h3 {
            margin: 0;
            font-size: 13px;
            flex-grow: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .book-item button {
            padding: 2px 6px;
            margin-left: 8px;
            font-size: 10px;
        }
        button {
            background-color: #4CAF50;
            color: white;
            padding: 8px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 3px;
        }
        button:hover {
            background-color: #45a049;
        }
        .view-button {
            background-color: #2196F3;
        }
        .view-button:hover {
            background-color: #0b7dda;
        }
        .delete-button {
            background-color: #f44336;
        }
        .delete-button:hover {
            background-color: #d32f2f;
        }
        .file-info {
            margin: 8px 0;
            padding: 8px;
            background-color: #f9f9f9;
            border-radius: 4px;
        }
        .controls {
            margin: 12px 0;
        }
        .book-selector {
            margin: 12px 0;
        }
        select {
            padding: 4px;
            margin: 0 4px;
        }
        .content-viewer {
            border: 1px solid #ddd;
            padding: 12px;
            border-radius: 4px;
            background-color: #f9f9f9;
            height: 100%;
            box-sizing: border-box;
        }
        .content-viewer img {
            max-width: 100%;
            max-height: 85vh;
            cursor: grab;
            display: block;
            margin: 0 auto;
        }
        .content-viewer img:active {
            cursor: grabbing;
        }
        .content-viewer pre {
            white-space: pre-wrap;
            word-wrap: break-word;
            background-color: white;
            padding: 8px;
            border-radius: 3px;
            max-height: 85vh;
            overflow-y: auto;
            margin: 0;
        }
        .viewer-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }
        .close-viewer {
            background-color: #f44336;
            color: white;
            border: none;
            padding: 4px 8px;
            cursor: pointer;
            border-radius: 3px;
        }
        .viewer-content {
            min-height: 800px;
        }
        .font-size-control {
            margin: 8px 0;
        }
        .font-size-control input {
            width: 50px;
            padding: 4px;
            margin: 0 4px;
        }
        .font-size-control label {
            font-size: 14px;
        }
        /* 图片放大查看器 */
        .image-modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.9);
        }
        .image-modal-content {
            margin: auto;
            width: 80%;
            max-width: 700px;
            max-height: 80%;
            position: absolute;
            top: 50%;
            left: 0%;
            transform: translate(-50%, -50%);
        }
        .modal-image-container {
            width:300%;
            height: 80vh;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            cursor: grab;
            user-select: none;
        }
        .modal-image-container:active {
            cursor: grabbing;
        }
        .modal-image-container img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }
        .close-modal {
            position: absolute;
            top: 15px;
            right: 35px;
            color: #f1f1f1;
            font-size: 40px;
            font-weight: bold;
            cursor: pointer;
        }
        .close-modal:hover {
            color: #bbb;
        }
        .zoom-controls {
            position: absolute;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            color: white;
            background-color: rgba(0,0,0,0.5);
            padding: 10px;
            border-radius: 5px;
        }
        .zoom-controls button {
            margin: 0 5px;
            padding: 5px 10px;
        }
        .loading {
            text-align: center;
            padding: 20px;
        }
    </style>
</head>
<body>
    <a href="../index.html" class="back-link">← 返回主页</a>
    <h1>读书室</h1>
    
    <div class="upload-area" id="dropArea">
        <p>点击选择文件或拖拽文件到此处</p>
        <p>支持文本文件(.txt)和图片文件(.jpg, .png, .gif)</p>
        <input type="file" id="fileInput" multiple accept=".txt,.jpg,.jpeg,.png,.gif" style="display: none;">
    </div>
    
    <div class="controls">
        <button id="saveBook">保存为书卷</button>
        <div class="book-selector">
            <label>选择书卷:</label>
            <select id="bookSelector"></select>
            <button id="loadBook">打开书卷</button>
            <button id="deleteBook">删除书卷</button>
        </div>
        <button id="clearAll">清空当前</button>
    </div>
    
    <div class="font-size-control">
        <label>内容字体大小:</label>
        <input type="number" id="fontSizeInput" value="32" min="8" max="72">
        <button id="applyFontSize">应用</button>
    </div>
    
    <div class="main-container">
        <div class="book-list" id="bookList">
            <h2>当前书卷内容:</h2>
            <div id="fileInfo"></div>
            <div id="filesContainer"></div>
        </div>
        
        <div class="content-viewer-container">
            <div class="content-viewer" id="contentViewer">
                <div class="viewer-header">
                    <h3 id="viewerTitle">请选择文件查看内容</h3>
                </div>
                <div class="viewer-content" id="viewerContent">
                    <p>请从左侧文件列表中选择一个文件查看内容</p>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 图片放大查看器 -->
    <div id="imageModal" class="image-modal">
        <span class="close-modal">&times;</span>
        <div class="image-modal-content">
            <div class="modal-image-container" id="modalImageContainer">
                <img id="modalImage">
            </div>
        </div>
        <div class="zoom-controls">
            <button id="zoomIn">放大</button>
            <button id="zoomOut">缩小</button>
            <button id="resetZoom">重置</button>
        </div>
    </div>

    <script>
        let bookFiles = [];
        let currentBookName = '';
        let currentBookId = null;
        let currentFontSize = 32;
        let currentImageScale = 1;
        let modalImage = null;
        let isDragging = false;
        let startX, startY;
        let startTransformX = 0, startTransformY = 0;
        let transformX = 0, transformY = 0;
        
        // API基础URL - 使用本地服务器
        const API_BASE = 'http://localhost:8000';
        
        const dropArea = document.getElementById('dropArea');
        const fileInput = document.getElementById('fileInput');
        const saveBookBtn = document.getElementById('saveBook');
        const loadBookBtn = document.getElementById('loadBook');
        const deleteBookBtn = document.getElementById('deleteBook');
        const filesContainer = document.getElementById('filesContainer');
        const fileInfo = document.getElementById('fileInfo');
        const clearAllBtn = document.getElementById('clearAll');
        const bookSelector = document.getElementById('bookSelector');
        const contentViewer = document.getElementById('contentViewer');
        const viewerTitle = document.getElementById('viewerTitle');
        const viewerContent = document.getElementById('viewerContent');
        const fontSizeInput = document.getElementById('fontSizeInput');
        const applyFontSizeBtn = document.getElementById('applyFontSize');
        const imageModal = document.getElementById('imageModal');
        const modalImg = document.getElementById('modalImage');
        const modalImgContainer = document.getElementById('modalImageContainer');
        const closeModal = document.querySelector('.close-modal');
        const zoomInBtn = document.getElementById('zoomIn');
        const zoomOutBtn = document.getElementById('zoomOut');
        const resetZoomBtn = document.getElementById('resetZoom');
        
        // 页面加载时初始化
        window.addEventListener('DOMContentLoaded', () => {
            updateBookSelector();
        });
        
        // 字体大小控制
        applyFontSizeBtn.addEventListener('click', () => {
            currentFontSize = parseInt(fontSizeInput.value) || 16;
            // 更新当前显示的内容字体大小
            const preElement = viewerContent.querySelector('pre');
            if (preElement) {
                preElement.style.fontSize = currentFontSize + 'px';
            }
        });
        
        // 图片放大功能
        viewerContent.addEventListener('click', (e) => {
            if (e.target.tagName === 'IMG') {
                openImageModal(e.target.src);
            }
        });
        
        // 打开图片放大查看器
        function openImageModal(src) {
            modalImg.src = src;
            imageModal.style.display = 'block';
            currentImageScale = 1;
            transformX = 0;
            transformY = 0;
            updateImageTransform();
        }
        
        // 关闭图片放大查看器
        closeModal.onclick = function() {
            imageModal.style.display = 'none';
        }
        
        // 点击模态框外部关闭
        window.onclick = function(event) {
            if (event.target == imageModal) {
                imageModal.style.display = 'none';
            }
        }
        
        // 缩放控制
        zoomInBtn.addEventListener('click', () => {
            currentImageScale *= 1.2;
            updateImageTransform();
        });
        
        zoomOutBtn.addEventListener('click', () => {
            currentImageScale *= 0.8;
            updateImageTransform();
        });
        
        resetZoomBtn.addEventListener('click', () => {
            currentImageScale = 1;
            transformX = 0;
            transformY = 0;
            updateImageTransform();
        });
        
        // 图片拖动功能
        modalImgContainer.addEventListener('mousedown', startDrag);
        window.addEventListener('mousemove', drag);
        window.addEventListener('mouseup', endDrag);
        
        function startDrag(e) {
            if (e.target !== modalImgContainer && !modalImg.contains(e.target)) return;
            
            isDragging = true;
            startX = e.clientX;
            startY = e.clientY;
            startTransformX = transformX;
            startTransformY = transformY;
            
            modalImgContainer.style.cursor = 'grabbing';
            e.preventDefault();
        }
        
        function drag(e) {
            if (!isDragging) return;
            
            const dx = e.clientX - startX;
            const dy = e.clientY - startY;
            
            transformX = startTransformX + dx;
            transformY = startTransformY + dy;
            
            updateImageTransform();
        }
        
        function endDrag() {
            if (isDragging) {
                isDragging = false;
                modalImgContainer.style.cursor = 'grab';
            }
        }
        
        // 更新图片变换（缩放和位置）
        function updateImageTransform() {
            modalImg.style.transform = `translate(${transformX}px, ${transformY}px) scale(${currentImageScale})`;
        }
        
        // 点击上传区域选择文件
        dropArea.addEventListener('click', () => {
            fileInput.click();
        });
        
        // 文件选择事件
        fileInput.addEventListener('change', handleFileSelect);
        
        // 拖拽上传功能
        dropArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropArea.style.backgroundColor = '#e0e0e0';
        });
        
        dropArea.addEventListener('dragleave', () => {
            dropArea.style.backgroundColor = '';
        });
        
        dropArea.addEventListener('drop', (e) => {
            e.preventDefault();
            dropArea.style.backgroundColor = '';
            if (e.dataTransfer.files.length) {
                handleFiles(e.dataTransfer.files);
            }
        });
        
        // 处理选择的文件
        function handleFileSelect(e) {
            if (e.target.files.length) {
                handleFiles(e.target.files);
            }
        }
        
        function handleFiles(files) {
            // 显示文件处理进度
            const progressElement = document.createElement('div');
            progressElement.className = 'loading';
            progressElement.innerHTML = `<p>正在处理 ${files.length} 个文件...</p>`;
            filesContainer.appendChild(progressElement);
            
            let processedCount = 0;
            const totalFiles = files.length;
            
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                const reader = new FileReader();
                
                reader.onload = (e) => {
                    const fileData = {
                        name: file.name,
                        type: file.type,
                        size: file.size,
                        lastModified: file.lastModified,
                        content: e.target.result
                    };
                    
                    bookFiles.push(fileData);
                    processedCount++;
                    
                    // 更新进度
                    progressElement.innerHTML = `<p>正在处理文件: ${processedCount}/${totalFiles}</p>`;
                    
                    // 处理完成后更新文件列表
                    if (processedCount === totalFiles) {
                        progressElement.remove();
                        // 对文件进行排序
                        sortFiles();
                        updateFileList();
                    }
                };
                
                reader.onerror = () => {
                    processedCount++;
                    console.error(`文件 ${file.name} 处理失败`);
                    if (processedCount === totalFiles) {
                        progressElement.remove();
                        // 对文件进行排序
                        sortFiles();
                        updateFileList();
                    }
                };
                
                if (file.type.startsWith('image/')) {
                    reader.readAsDataURL(file);
                } else if (file.type === 'text/plain' || file.name.endsWith('.txt')) {
                    reader.readAsText(file, 'GBK');
                } else {
                    // 对于其他类型文件，也以文本形式读取
                    reader.readAsText(file, 'GBK');
                }
            }
        }
        
        // 根据文件名开头的数字进行排序
        function sortFiles() {
            bookFiles.sort((a, b) => {
                // 提取文件名开头的数字
                const numA = extractLeadingNumber(a.name);
                const numB = extractLeadingNumber(b.name);
                
                // 如果都能提取到数字，则按数字排序
                if (numA !== null && numB !== null) {
                    return numA - numB;
                }
                
                // 如果只有一个能提取到数字，有数字的排在前面
                if (numA !== null && numB === null) {
                    return -1;
                }
                if (numA === null && numB !== null) {
                    return 1;
                }
                
                // 如果都提取不到数字，按文件名排序
                return a.name.localeCompare(b.name);
            });
        }
        
        // 提取文件名开头的数字
        function extractLeadingNumber(filename) {
            // 匹配文件名开头的一个或多个数字
            const match = filename.match(/^(\d+)/);
            return match ? parseInt(match[1]) : null;
        }
        
        // 更新文件列表显示
        function updateFileList() {
            // 显示文件统计信息
            fileInfo.innerHTML = `
                <div class="file-info">
                    <p>总共导入文件数: ${bookFiles.length}</p>
                </div>
            `;
            
            // 显示文件列表（只显示文件名）
            filesContainer.innerHTML = '';
            bookFiles.forEach((file, index) => {
                const fileElement = document.createElement('div');
                fileElement.className = 'book-item';
                fileElement.innerHTML = `
                    <h3>${file.name}</h3>
                    <button class="view-button" data-index="${index}">查看</button>
                `;
                filesContainer.appendChild(fileElement);
            });
            
            // 为查看按钮添加事件监听器
            document.querySelectorAll('.view-button').forEach(button => {
                button.addEventListener('click', (e) => {
                    const index = parseInt(e.target.getAttribute('data-index'));
                    viewFileContent(index);
                });
            });
        }
        
        // 查看文件内容
        function viewFileContent(index) {
            const file = bookFiles[index];
            if (!file) return;
            
            viewerTitle.textContent = `文件: ${file.name}`;
            
            if (file.type.startsWith('image/')) {
                // 对于图片文件，直接显示
                viewerContent.innerHTML = `<img src="${file.content}" alt="${file.name}" style="display: block; margin: 0 auto; max-width: 100%;">`;
            } else {
                // 对于文本文件，直接显示内容
                viewerContent.innerHTML = `<pre style="font-size: ${currentFontSize}px;">${file.content}</pre>`;
            }
        }
        
        // 保存书卷到本地服务器
        saveBookBtn.addEventListener('click', () => {
            if (bookFiles.length === 0) {
                alert('请先添加文件');
                return;
            }
            
            const bookName = prompt('请输入书卷名称:', `书卷_${new Date().toLocaleString()}`);
            if (!bookName) {
                return;
            }
            
            // 显示保存进度
            const progressElement = document.createElement('div');
            progressElement.className = 'loading';
            progressElement.innerHTML = '<p>正在保存书卷...</p>';
            document.body.appendChild(progressElement);
            
            // 发送到本地服务器保存
            fetch(`${API_BASE}/api/save-book`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    name: bookName,
                    files: bookFiles
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                progressElement.remove();
                if (data.success) {
                    alert(`成功保存书卷: ${bookName}`);
                    currentBookName = bookName;
                    updateBookSelector();
                } else {
                    alert('保存失败: ' + data.message);
                }
            })
            .catch(error => {
                progressElement.remove();
                console.error('保存错误:', error);
                alert('保存失败: ' + error.message);
            });
        });
        
        // 更新书卷选择器
        function updateBookSelector() {
            fetch(`${API_BASE}/api/list-books`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    bookSelector.innerHTML = '';
                    data.books.forEach(book => {
                        const option = document.createElement('option');
                        option.value = book.id;
                        option.textContent = `${book.name} (${book.file_count}个文件)`;
                        bookSelector.appendChild(option);
                    });
                } else {
                    console.error('获取书籍列表失败:', data.message);
                    alert('获取书籍列表失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('获取书籍列表失败:', error);
                alert('获取书籍列表失败: ' + error.message);
            });
        }
        
        // 打开书卷
        loadBookBtn.addEventListener('click', () => {
            const selectedBookId = bookSelector.value;
            if (!selectedBookId) {
                alert('请先选择一个书卷');
                return;
            }
            
            // 显示加载进度
            const progressElement = document.createElement('div');
            progressElement.className = 'loading';
            progressElement.innerHTML = '<p>正在加载书卷...</p>';
            document.body.appendChild(progressElement);
            
            fetch(`${API_BASE}/api/load-book/${selectedBookId}`)
            .then(response => response.json())
            .then(data => {
                progressElement.remove();
                if (data.success) {
                    loadBook(data);
                } else {
                    alert('书卷加载失败: ' + data.message);
                }
            })
            .catch(error => {
                progressElement.remove();
                alert('书卷加载失败: ' + error.message);
            });
        });
        
        // 删除书卷
        deleteBookBtn.addEventListener('click', () => {
            const selectedBookId = bookSelector.value;
            if (!selectedBookId) {
                alert('请先选择一个书卷');
                return;
            }
            
            const selectedOption = bookSelector.options[bookSelector.selectedIndex];
            const bookName = selectedOption.text.split(' (')[0];
            
            if (confirm(`确定要删除书卷 "${bookName}" 吗？`)) {
                // 显示删除进度
                const progressElement = document.createElement('div');
                progressElement.className = 'loading';
                progressElement.innerHTML = '<p>正在删除书卷...</p>';
                document.body.appendChild(progressElement);
                
                fetch(`${API_BASE}/api/delete-book`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        id: selectedBookId
                    })
                })
                .then(response => response.json())
                .then(data => {
                    progressElement.remove();
                    if (data.success) {
                        alert(`书卷 "${bookName}" 已删除`);
                        updateBookSelector();
                    } else {
                        alert('删除失败: ' + data.message);
                    }
                })
                .catch(error => {
                    progressElement.remove();
                    alert('删除失败: ' + error.message);
                });
            }
        });
        
        // 加载书卷内容
        function loadBook(data) {
            const book = data.book;
            const files = data.files;
            
            // 保存书籍信息
            currentBookId = book.id;
            currentBookName = book.name;
            
            // 构造bookFiles数组
            bookFiles = files.map(file => ({
                id: file.id,
                name: file.filename,
                type: file.file_type,
                size: parseInt(file.file_size),
                sort_order: parseInt(file.sort_order)
            }));
            
            // 更新文件列表
            updateFileList();
            alert(`成功加载书卷: ${book.name}，包含 ${book.file_count} 个文件`);
        }
        
        // 清空所有文件
        clearAllBtn.addEventListener('click', () => {
            if (bookFiles.length > 0 && confirm('确定要清空当前所有已导入的文件吗？')) {
                bookFiles = [];
                updateFileList();
            }
        });
    </script>
</body>
</html>